package cn.tedu.charging.order.rabbitmq;

import cn.tedu.charging.order.config.RabbitMQConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class RabbitMQProducer {
    private static final Logger log = LoggerFactory.getLogger(RabbitMQProducer.class);
    @Autowired
    private RabbitTemplate rabbitTemplate;

    /**
     * 发送消息
     * @param msg
     */
    public void send(String msg) {
        //设置消息发送的确认回调类
        //判断ACK的结果，如果true表示消息发送成功，否则表示消息发送失败
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            if (ack) {
                log.debug("消息发送成功,RabbitMQ成功收到了生产者发送的消息");
            }else {
                log.debug("消息发送失败,RabbitMQ没有收到生产者发送的消息");
                log.debug("失败原因:{}",cause);
                log.debug("如果失败要进行重试,重试几次后,不成功,监控告警,重试有可能导致消息重复");
            }
        });
        //消息持久化
        Message message = new Message(msg.getBytes(),new MessageProperties());
        message.getMessageProperties().setDeliveryMode(MessageDeliveryMode.PERSISTENT);


        rabbitTemplate
                .convertAndSend
                        (RabbitMQConfiguration.ORDER_EXCHANGE,
                                RabbitMQConfiguration.ORDER_ROUTING_KEY, message);
        log.debug("消息发送成功,消息内容:{}",message);
        //channel.basicPublish(exchange,routingKey,null,message.getBytes());
    }

}
